import React, { Component } from 'react';
import { SearchBar, Tabs, Toast, ActivityIndicator, Tag } from 'antd-mobile';
import {
	searchAudio,
	searchAlbum,
	getDeviceId,
	getUuid,
	convetAudios,
	convetAlbums,
	getDeviceSn,
	getPrimaryAlbumList
} from '../utils.js';
import SearchAudioList from '../components/SearchAudioList';
import AlbumListBySearch from '../components/AlbumListBySearch';
import '../css/MySearchBar.css';
import { CACHE_TMP_SEARCH_AUDIOS, CACHE_TMP_SEARCH_ALBUMS, CACHE_TMP_SEARCH_TAB_INDEX } from '../config';

// 搜索界面
class MySearchBar extends Component {

	constructor(props) {
		super(props);
		this.handleChange = this.handleChange.bind(this);
		this.handleSubmit = this.handleSubmit.bind(this);
		this.handleCancle = this.handleCancle.bind(this);

		// 搜索Tag
		this.searchTags = [];
		const tags = localStorage.getItem("search_tags");
		if (tags) {
			this.searchTags = tags.split(',');
		}		
		// 存储用户搜索词
		const records = localStorage.getItem("search_records");
		let words = [];
		if (records) {
			words = records.split(",");
		}
		// 获取上次搜索的缓存数据
		const cacheList = this.loadSearchCahche();
		let tabs = [];
		let showTags = true;
		let searchAudioList = [];
		let searchAlbumList = [];
		let currentIndex = 0;
		let tabIndexStr = sessionStorage.getItem(CACHE_TMP_SEARCH_TAB_INDEX);
		if (tabIndexStr) {
			currentIndex = parseInt(tabIndexStr,10);
		}
		if (cacheList.length > 0) {
			tabs = [{ title: "单曲" }, { title: "专辑" }];
			showTags = false;
			searchAudioList = cacheList[0];
			searchAlbumList = cacheList[1];
		}

		this.state = {
			searchAudioList: searchAudioList,
			searchAlbumList: searchAlbumList,
			tabs: tabs,
			keywords: '',
			searching: false,
			showTags: showTags,
			words: words,
			uuid: getUuid(),
			currentIndex:currentIndex
		}
	}

	/**
	 * 显示搜索的数据
	 */
	loadSearchCahche(){
		let list = [];
		const cacheAudios = sessionStorage.getItem(CACHE_TMP_SEARCH_AUDIOS);
		if (cacheAudios) {
			list.push(JSON.parse(cacheAudios));
		}
		const cachAlbums = sessionStorage.getItem(CACHE_TMP_SEARCH_ALBUMS);
		if (cachAlbums) {
			list.push(JSON.parse(cachAlbums));
		}
		return list;
	}


	componentDidMount() {
		this.autoFocusInst.focus();
		getPrimaryAlbumList().then((data) => {
			const albums = JSON.stringify(data);
			localStorage.setItem('filter_album',albums);
		});
	}

	handleSubmit() {
		if (getDeviceSn().length === 0) {
			Toast.show('未绑定设备', 1, false);
			return;
		}
		if (this.state.keywords === '') {
			Toast.info('未输入搜索关键词', 1)
			return
		}
		this.handleSearch(this.state.keywords);
	}


	searchAudios(uuid, words) {
		return new Promise(function (resolve, reject) {
			searchAudio(uuid, words, 1, (result) => {
				let audios = [];
				if (result.errcode === 0 && result.data) {
					audios = convetAudios(result.data);
				}
				resolve(audios);
			})
		});
	}

	searchAlbums(uuid, words) {
		return new Promise(function (resolve, reject) {
			searchAlbum(uuid, words, 1, (result) => {
				let albums = [];
				if (result.errcode === 0 && result.data) {
					albums = convetAlbums(result.data);
				}
				resolve(albums);
			})
		});
	}



	handleSearch(words) {
		this.setState({ searching: true });
		let uuid = this.state.uuid;
		Promise.all([this.searchAudios(uuid, words), this.searchAlbums(uuid, words)]).then((values) => {
			this.setState({
				tabs: [{ title: "单曲" }, { title: "专辑" }],
				searchAudioList: values[0],
				searchAlbumList: values[1],
				searching: false,
				showTags: false
			});
			this.updateHistoryRecords(words);
		});
	}

	// 更新搜索关键词记录
	updateHistoryRecords(words) {
		let records = localStorage.getItem("search_records");
		if (records === null) {
			localStorage.setItem("search_records", words);
		} else {
			let hasExists = false;
			let historyRecords = records.split(",");
			historyRecords.forEach(item => {
				if (item === words) {
					hasExists = true;
				}
			})
			// 不存在相同搜索关键词才新增，并且需要限制搜索的关键词展示的个数
			if (!hasExists) {
				if (historyRecords.length >= 10) {
					records = records.substring(historyRecords[0].length + 1, records.length);
				}
				records += "," + words;
				localStorage.setItem("search_records", records);
			}
		}
	}


	// 取消按钮关闭当前视图
	handleCancle() {
		this.setState({
			keywords: ''
		})
		this.props.history.goBack();
	}
	// 更新输入信息
	handleChange(text, e) {
		this.setState({ keywords: text });
	}

	handleItemAlbum(item) {
		// 处理缓存
		sessionStorage.setItem(CACHE_TMP_SEARCH_AUDIOS,JSON.stringify(this.state.searchAudioList));
		sessionStorage.setItem(CACHE_TMP_SEARCH_ALBUMS,JSON.stringify(item.album_list));
		sessionStorage.setItem(CACHE_TMP_SEARCH_TAB_INDEX,1);
		this.props.history.push({
			pathname: '/album',
			device_id: this.props.location.device_id,
			album: item.album,
			fromBaidu: true,
		});
	}

	tagChange(txt, selected) {
		if (getDeviceSn().length === 0) {
			Toast.show('未绑定设备', 1, false);
			return;
		}
		this.setState({ keywords: txt });
		this.handleSearch(txt);
	}

	render() {
		return (
			<div style={{ width: '100%', height: '100%' }}>
				<SearchBar
					ref={ref => this.autoFocusInst = ref}
					defaultValue=""
					value={this.state.keywords}
					placeholder="输入要查询的故事或专辑"
					showCancelButton={true}
					onSubmit={this.handleSubmit}
					onChange={this.handleChange}
					onCancel={this.handleCancle}
				/>

				{
					this.state.showTags &&
					<div>
						<div style={{ margin: 10, fontSize: '13px', color: '#757575' }}>热门搜索</div>
						<div className="MySearchBar-tag-container" style={{ marginLeft: 10 }}>
							{
								this.searchTags.map(txt => {
									return (
										<Tag key={txt} onChange={this.tagChange.bind(this, txt)}
											style={{ margin: 5 }}>{txt}</Tag>)
								})
							}
						</div>
						<div style={{ margin: 10, fontSize: '13px', color: '#757575' }}>历史搜索</div>
						<div className="MySearchBar-tag-container" style={{ marginLeft: 10 }}>
							{
								this.state.words.map((txt, index) => {
									return (
										<Tag key={txt} onChange={this.tagChange.bind(this, txt)}
											style={{ margin: 5 }}>{txt}</Tag>
									)
								})
							}
						</div>
					</div>
				}

				{
					this.state.tabs.length > 0 &&
					<Tabs
						useOnPan={false}
						tabs={this.state.tabs}
						initialPage={this.state.currentIndex}
						tabBarActiveTextColor="#15a67c"
						tabBarInactiveTextColor="#9E9E9E"
						tabBarUnderlineStyle={{ borderColor: '#15a67c', height: '1px' }}>
						<div style={{ height: '100%', background: '#ffffff' }}>
							<SearchAudioList
								device_id={getDeviceId()}
								keywords={this.state.keywords}
								audio_list={this.state.searchAudioList}
							/>
						</div>
						<div style={{ height: '100%', background: '#ffffff' }}>
							<AlbumListBySearch
								keywords={this.state.keywords}
								album_list={this.state.searchAlbumList}
								handleItemAlbum={this.handleItemAlbum.bind(this)} />
						</div>
					</Tabs>
				}
				{
					this.state.searching &&
					<ActivityIndicator
						toast
						text="加载中..."
						animating={this.state.searching}
					/>
				}


			</div >

		);
	}
};
export default MySearchBar;


